#include "StdAfx.h"
#include "app_log.h"
#include <stdarg.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <shlwapi.h>

static char app_log_file[_MAX_PATH];
static const int log_max_size = (1<<20) * 32;

extern __int64 getfilesize(const char *name);

void 
app_comm_log(const char *format, ...)
{
    if (app_log_file[0] == '\0') {
        ::GetModuleFileName(NULL, app_log_file, sizeof(app_log_file) - 1);
        ::PathRemoveFileSpec(app_log_file);
        ::lstrcat(app_log_file, "\\IndexMonitor.log");
    }
    FILE *stream = NULL;

    if (getfilesize(app_log_file) >= log_max_size)
        stream = fopen(app_log_file, "w+");
    else
        stream = fopen(app_log_file, "a+");
    assert(stream);
    va_list args;
    va_start(args, format);

    char datetime[80] = { 0 };
    time_t t = ::time(NULL);
    struct tm *ltm  = ::localtime(&t);
    ::strftime(datetime, sizeof(datetime) - 1,
        "%Y/%m/%d %H:%M:%S", ltm);
    ::fprintf(stream, "[%s] ", datetime);
    ::vfprintf(stream, format, args);
    va_end(args);

    fclose(stream);
}